package com.gen.generator.ui;

import com.gen.generator.config.CodeGenConfig;
import com.gen.generator.util.DBUtil;
import com.gen.generator.util.ErrorUtil;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.util.ui.JBUI;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import static com.gen.generator.util.ErrorUtil.showError;

public class ConfigDialog extends JDialog {

    public final JTextField hostField = new JTextField("localhost");
    public final JTextField portField = new JTextField("3306");
    public final JTextField dbField = new JTextField();
    public final JTextField userField = new JTextField("root");
    public final JPasswordField passField = new JPasswordField();
    public final JTextField tableField = new JTextField();
    public final JTextField packageField = new JTextField("com.generated");
    public final JTextField outputDirField = new JTextField(System.getProperty("user.home") + "\\Generated");
    public final JTextField authorField = new JTextField("author");
    public final ComboBox<String> tenantCombo = new ComboBox<>(new String[]{"否", "是"});

    {
        tenantCombo.setSelectedItem("是");
    }

    private boolean confirmed = false;

    public ConfigDialog(Frame owner) {
        super(owner, "MySQL 代码生成", true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setSize(1000, 400);
        setLocationRelativeTo(owner);
        setLayout(new BorderLayout());
        setFont(new Font("微软雅黑", Font.PLAIN, 14));

        // IDEA主题颜色
        Color panelBg = UIManager.getColor("Panel.background");
        Color fieldBg = UIManager.getColor("TextField.background");
        Color fieldFg = UIManager.getColor("TextField.foreground");
        Color btnBg = UIManager.getColor("Button.background");
        Color btnFg = UIManager.getColor("Button.foreground");

        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        mainPanel.setBackground(panelBg);
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(10, 10, 10, 10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1.0;

        int row = 0;

        // 数据库配置块
        JPanel dbPanel = new JPanel(new GridBagLayout());
        dbPanel.setBorder(new TitledBorder("数据库配置"));
        dbPanel.setBackground(panelBg);
        panelAdd3Aligned(dbPanel, 0, "主机", hostField, "端口", portField, "数据库名", dbField);
        panelAdd3Aligned(dbPanel, 1, "用户名", userField, "密码", passField, "表名", tableField);
        c.gridx = 0; c.gridy = row++; c.gridwidth = 1; mainPanel.add(dbPanel, c);

        // 生成配置块
        JPanel codePanel = new JPanel(new GridBagLayout());
        codePanel.setBorder(new TitledBorder("生成配置"));
        codePanel.setBackground(panelBg);
        panelAdd3Aligned(codePanel, 0, "包路径", packageField, "作者", authorField, "是否多租户", tenantCombo);

        // 输出目录单独一行（加标签）
        JButton chooseOutput = new JButton("选择...");
        chooseOutput.setFocusPainted(false);
        chooseOutput.setBackground(btnBg);
        chooseOutput.setForeground(btnFg);
        chooseOutput.addActionListener(this::chooseOutputDir);

        JPanel outPanel = new JPanel(new GridBagLayout());
        outPanel.setBackground(panelBg);
        GridBagConstraints cOut = new GridBagConstraints();
        cOut.insets = JBUI.insets(5);
        cOut.fill = GridBagConstraints.HORIZONTAL;
        cOut.gridy = 0;

        // 标签
        cOut.gridx = 0; cOut.weightx = 0.2; cOut.anchor = GridBagConstraints.EAST;
        outPanel.add(new JLabel("输出目录:"), cOut);

        // 输入框
        cOut.gridx = 1; cOut.weightx = 0.6; cOut.anchor = GridBagConstraints.WEST;
        outPanel.add(outputDirField, cOut);

        // 按钮
        cOut.gridx = 2; cOut.weightx = 0.2; cOut.anchor = GridBagConstraints.WEST;
        outPanel.add(chooseOutput, cOut);

        // 添加到 codePanel
        GridBagConstraints c2 = new GridBagConstraints();
        c2.gridx = 0; c2.gridy = 1; c2.gridwidth = 6; c2.fill = GridBagConstraints.HORIZONTAL; c2.weightx = 1.0;
        codePanel.add(outPanel, c2);

        c.gridx = 0; c.gridy = row++; c.gridwidth = 1; mainPanel.add(codePanel, c);

        add(mainPanel, BorderLayout.CENTER);

        // 底部按钮
        JPanel btns = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        btns.setBackground(panelBg);
        JButton testBtn = new JButton("测试连接");
        JButton genBtn = new JButton("生成");
        JButton closeBtn = new JButton("关闭");

        JButton[] buttons = {testBtn, genBtn, closeBtn};
        for (JButton btn : buttons) {
            btn.setBackground(btnBg);
            btn.setForeground(btnFg);
            btn.setFocusPainted(false);
            btn.setFont(new Font("微软雅黑", Font.BOLD, 13));
        }

        testBtn.addActionListener(this::testConnection);
        genBtn.addActionListener(e -> { confirmed = true; dispose(); });
        closeBtn.addActionListener(e -> dispose());

        btns.add(testBtn);
        btns.add(genBtn);
        btns.add(closeBtn);
        add(btns, BorderLayout.SOUTH);

        // 输入框颜色适配
        JTextField[] fields = {hostField, portField, dbField, userField, passField, tableField, packageField, outputDirField, authorField};
        for (JTextField f : fields) {
            f.setBackground(fieldBg);
            f.setForeground(fieldFg);
            f.setCaretColor(fieldFg);
        }
        tenantCombo.getEditor().getEditorComponent().setBackground(fieldBg);
        tenantCombo.getEditor().getEditorComponent().setForeground(fieldFg);
    }

    /**
     * 三列布局，每列标签右对齐，输入框左对齐，宽度均等
     */
    private void panelAdd3Aligned(JPanel panel, int row,
                                  String label1, Component comp1,
                                  String label2, Component comp2,
                                  String label3, Component comp3) {
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 5, 5, 5);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = row;

        // 第一列
        c.gridx = 0; c.weightx = 0.2; c.anchor = GridBagConstraints.EAST; panel.add(new JLabel(label1 + ":"), c);
        c.gridx = 1; c.weightx = 0.5; c.anchor = GridBagConstraints.WEST; panel.add(comp1, c);

        // 第二列
        c.gridx = 2; c.weightx = 0.2; c.anchor = GridBagConstraints.EAST; panel.add(new JLabel(label2 + ":"), c);
        c.gridx = 3; c.weightx = 0.5; c.anchor = GridBagConstraints.WEST; panel.add(comp2, c);

        // 第三列
        c.gridx = 4; c.weightx = 0.2; c.anchor = GridBagConstraints.EAST; panel.add(new JLabel(label3 + ":"), c);
        c.gridx = 5; c.weightx = 0.5; c.anchor = GridBagConstraints.WEST; panel.add(comp3, c);
    }

    private void chooseOutputDir(ActionEvent e) {
        JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            outputDirField.setText(fc.getSelectedFile().getAbsolutePath());
        }
    }

    private void testConnection(ActionEvent e) {
        try (Connection conn = DBUtil.open(
                hostField.getText().trim(),
                portField.getText().trim(),
                dbField.getText().trim(),
                userField.getText().trim(),
                new String(passField.getPassword())
        )) {
            JOptionPane.showMessageDialog(this, "连接成功！", "Success", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            ErrorUtil.showError(ex,this);
        }
    }



    public boolean isConfirmed() {
        return confirmed;
    }

    public CodeGenConfig getConfig(List<Map<String, String>> templates) {
        if (!confirmed) return null;

        CodeGenConfig config = CodeGenConfig.builder()
                .host(hostField.getText().trim())
                .port(portField.getText().trim())
                .dbName(dbField.getText().trim())
                .username(userField.getText().trim())
                .password(new String(passField.getPassword()))
                .tableName(tableField.getText().trim())
                .packageName(packageField.getText().trim())
                .outputDir(outputDirField.getText().trim())
                .author(authorField.getText().trim())
                .templates(templates)
                .crud(true)
                .sub(false)
                .tree(false)
                .tenant("是".equals(tenantCombo.getItem().trim()))
                .build();
        return config;
    }
}
